package com.hifar.demo2;

import org.apache.poi.xwpf.usermodel.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.File;
import java.io.FileOutputStream;
import org.xml.sax.InputSource; // 添加缺失的导入语句
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import java.math.BigInteger;

public class TableToWordExporter {

    public static void exportTablesToWord(String xmlPath, String wordPath) {
        try {
            // 1. 解析XML文件（指定UTF-8编码）
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 使用InputSource指定编码
            InputSource is = new InputSource(new java.io.FileInputStream(xmlPath));
            is.setEncoding("UTF-8");
            org.w3c.dom.Document doc = builder.parse(is);

            // 2. 创建Word文档（默认UTF-8编码）
            XWPFDocument wordDoc = new XWPFDocument();

            // 3. 提取所有表格
            NodeList tables = doc.getElementsByTagName("table");
            for (int i = 0; i < tables.getLength(); i++) {
                Element tableElement = (Element) tables.item(i);

                // 添加表格标题
                // 修改表格标题处理部分，添加空值检查
                NodeList titleNodes = tableElement.getElementsByTagName("title");
                String title = "无标题表格";
                if (titleNodes.getLength() > 0 && titleNodes.item(0) != null) {
                    title = titleNodes.item(0).getTextContent();
                }

                XWPFParagraph titlePara = wordDoc.createParagraph();
                titlePara.createRun().setText(title);
                titlePara.setStyle("Heading2");

                // 创建Word表格
                NodeList rows = tableElement.getElementsByTagName("tr");

                // 2. 修改exportTablesToWord方法中的表格创建部分

                // 2. 在exportTablesToWord方法中调用
                XWPFTable wordTable = wordDoc.createTable(rows.getLength(), 0);
                beautifyTable(wordTable); // 应用美化样式

                // 4. 在processCell方法后调用
                // 此代码片段位置有误，缺少必要变量定义，应删除或移至合适位置
                // 此代码片段位置有误且 wordRow 未定义，将其移至单元格循环内调用
                // 填充表格内容

                // 修改后的表格处理逻辑
                for (int r = 0; r < rows.getLength(); r++) {
                    Element rowElement = (Element) rows.item(r);
                    NodeList cells = rowElement.getElementsByTagName("td");

                    XWPFTableRow wordRow = wordTable.getRow(r);
                    for (int c = 0; c < cells.getLength(); c++) {
                        Element cellElement = (Element) cells.item(c);

                        // 添加单元格
                        if (wordRow.getTableCells().size() <= c) {
                            wordRow.addNewTableCell();
                        }

                        // 处理单元格内容及合并
                        new TableToWordExporter().processCell(cellElement, wordRow.getCell(c), wordRow, c);
                    }
                }

                // 添加表格后空行
                wordDoc.createParagraph();
            }

            // 4. 保存Word文档（指定UTF-8编码）
            FileOutputStream out = new FileOutputStream(wordPath);
            wordDoc.write(out);
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 1. 添加自动调整列宽方法
    private static void autoAdjustColumnWidths(XWPFTable table) {
        // 计算每列最大宽度
        int[] colWidths = new int[table.getRow(0).getTableCells().size()];

        for (XWPFTableRow row : table.getRows()) {
            for (int i = 0; i < row.getTableCells().size(); i++) {
                XWPFTableCell cell = row.getTableCells().get(i);
                int contentLength = cell.getText().length();
                if (contentLength > colWidths[i]) {
                    colWidths[i] = contentLength;
                }
            }
        }

        // 设置列宽（按比例分配，最大不超过30%）
        int totalWidth = 0;
        for (int width : colWidths) {
            totalWidth += width;
        }

        for (int i = 0; i < colWidths.length; i++) {
            int widthPercent = (int) ((colWidths[i] * 100.0 / totalWidth) * 5000);
            widthPercent = Math.min(widthPercent, 1500); // 限制最大30%

            for (XWPFTableRow row : table.getRows()) {
                if (i < row.getTableCells().size()) {
                    CTTblWidth cellWidth = row.getCell(i).getCTTc().addNewTcPr().addNewTcW();
                    cellWidth.setType(STTblWidth.PCT);
                    cellWidth.setW(BigInteger.valueOf(widthPercent));
                }
            }
        }
    }

    // 3. 添加单元格内容样式设置
    private static void beautifyCellContent(XWPFTableCell cell) {
        // 设置垂直居中
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

        // 设置段落样式
        for (XWPFParagraph p : cell.getParagraphs()) {
            p.setAlignment(ParagraphAlignment.CENTER);

            // 设置字体样式
            for (XWPFRun r : p.getRuns()) {
                r.setFontFamily("微软雅黑");
                r.setFontSize(10);
                r.setColor("333333");
            }
        }
    }

    // 1. 添加表格样式设置方法
    private static void beautifyTable(XWPFTable table) {
        // 设置表格宽度为100%
        CTTblWidth width = table.getCTTbl().addNewTblPr().addNewTblW();
        width.setType(STTblWidth.PCT);
        width.setW(BigInteger.valueOf(5000)); // 100%

        // 设置表格边框
        table.setTopBorder(XWPFTable.XWPFBorderType.SINGLE, 4, 0, "4BACC6");
        table.setBottomBorder(XWPFTable.XWPFBorderType.SINGLE, 4, 0, "4BACC6");
        table.setLeftBorder(XWPFTable.XWPFBorderType.SINGLE, 4, 0, "4BACC6");
        table.setRightBorder(XWPFTable.XWPFBorderType.SINGLE, 4, 0, "4BACC6");
        table.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "DEEBF7");
        table.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "DEEBF7");

        // 设置交替行颜色
        for (int i = 0; i < table.getNumberOfRows(); i++) {
            XWPFTableRow row = table.getRow(i);
            for (XWPFTableCell cell : row.getTableCells()) {
                // 设置单元格背景色
                cell.setColor(i % 2 == 0 ? "FFFFFF" : "F7F7F7");

                // 设置单元格边距
                cell.getCTTc().addNewTcPr().addNewTcMar().addNewTop().setW(new java.math.BigInteger("100"));
                cell.getCTTc().addNewTcPr().addNewTcMar().addNewBottom().setW(new java.math.BigInteger("100"));
                cell.getCTTc().addNewTcPr().addNewTcMar().addNewLeft().setW(new java.math.BigInteger("100"));
                cell.getCTTc().addNewTcPr().addNewTcMar().addNewRight().setW(new java.math.BigInteger("100"));
            }
        }
    }

    private void processCell(Element cellElement, XWPFTableCell wordCell, XWPFTableRow wordRow, int colIndex) {
        // 处理单元格内容
        String cellText = getCellText(cellElement);
        wordCell.setText(cellText);

        // 处理colspan
        if (cellElement.hasAttribute("colspan")) {
            int colspan = Integer.parseInt(cellElement.getAttribute("colspan"));
            wordCell.getCTTc().addNewTcPr().addNewGridSpan().setVal(new java.math.BigInteger(String.valueOf(colspan)));
        }

        // 处理rowspan
        if (cellElement.hasAttribute("rowspan")) {
            int rowspan = Integer.parseInt(cellElement.getAttribute("rowspan"));
            wordCell.getCTTc().addNewTcPr().addNewVMerge()
                    .setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge.RESTART);

            for (int j = 1; j < rowspan; j++) {
                XWPFTableCell nextCell = wordRow.getCell(colIndex);
                nextCell.getCTTc().addNewTcPr().addNewVMerge()
                        .setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge.CONTINUE);
            }
        }
    }

    private static String getCellText(Element cellElement) {
        // 1. 首先检查para元素
        NodeList paras = cellElement.getElementsByTagName("para");
        if (paras.getLength() > 0) {
            return paras.item(0).getTextContent();
        }

        // 2. 处理backfillvalue元素
        NodeList backfills = cellElement.getElementsByTagName("backfillvalue");
        if (backfills.getLength() > 0) {
            Element backfill = (Element) backfills.item(0);
            String dataId = backfill.getAttribute("id");

            // 3. 从DATA-DXJG0001A.xml获取实际值
            String value = DataDxjg0001AParser.getValueById(
                    "src/main/resources/data/DATA-DXJG0001A.xml",
                    dataId);

            return value != null ? value : "[未找到值]" + dataId;
        }

        return "";
    }

    public static void main(String[] args) {
        TableToWordExporter.exportTablesToWord(
                "src/main/resources/data/DXJG0001A.xml",
                "output/tables.docx");
    }
}